package com.michale.framework.security.service;

import com.michale.common.utils.spring.SpringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author Michale
 * @apiNote 获取Anonymous注解的路径
 */
@Component
public class Anonymous {
    /**
     * 获取标有注解 AnonymousAccess 的访问路径
     */
    public static String[] getAnonymousUrls() {
        // 获取所有的 RequestMapping
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = SpringUtils.getBean(RequestMappingHandlerMapping.class).getHandlerMethods();
        Set<String> allAnonymousAccess = new HashSet<>();
        // 循环 RequestMapping
        for (Map.Entry<RequestMappingInfo, HandlerMethod> infoEntry : handlerMethods.entrySet()) {
            HandlerMethod value = infoEntry.getValue();
            // 获取方法上 Anonymous 类型的注解
            com.michale.common.annotation.Anonymous methodAnnotation = value.getMethodAnnotation(com.michale.common.annotation.Anonymous.class);
            // 如果方法上标注了 Anonymous 注解，就获取该方法的访问全路径
            if (methodAnnotation != null) {
                assert infoEntry.getKey().getPatternsCondition() != null;
                allAnonymousAccess.addAll(infoEntry.getKey().getPatternsCondition().getPatterns());
            }
        }
        return allAnonymousAccess.toArray(new String[0]);
    }
}
